<template>
  <v-page
    v-model="refreshing"
    background="#f5f6fa"
    footer-background="white"
    :loading="loading"
    @tolower="getList"
  >
    <template #header>
      <v-navbar
        title="全部评价"
        background-color="transparent"
        color="black"
      />
    </template>
    <template #default>
      <view class="comment-header">
        <view class="comment-title">
          <view class="comment-title-before_rate">
            {{ `${splitApplauseRate.before}.` }}
          </view>
          <view class="comment-title-after_rate">
            {{ `${splitApplauseRate.after}%` }}
          </view>
          <view class="comment-title-text">
            好评率
          </view>
        </view>

        <wd-rate
          v-model="score"
          color="#E1D5D7"
          active-color="linear-gradient(161.57deg, #FF6F6F 28.44%, #FF2F3B 75.31%);"
          readonly
        />
      </view>

      <view class="comment-subtitle">
        {{ `全部(${commentSum})` }}
      </view>

      <view class="comment-list">
        <product-comment-tag-list
          v-if="comments"
          :active="activeTag"
          :tag-list="tagList"
          @click-tag="clickTagHandle"
        />

        <product-comment-content
          v-for="comment in comments?.customer_comment"
          :key="comment.id"
          :comment="comment"
          my-comment
          show-thumb
          show-reply
          show-comment-time
        />
        <product-comment-content
          v-for="comment in commentList"
          :key="comment.id"
          :comment="comment"
          show-thumb
          show-reply
          show-comment-time
        />
        <product-comment-group-content
          v-for="comment in groupCommentList"
          :key="comment.id"
          :comment="comment"
          show-thumb
          show-reply
          show-comment-time
        />
      </view>

      <v-loadmore
        :state="state"
        @reload="getList"
      />
    </template>
    <template #footer>
      <view class="product-footer">
        <view
          v-if="tntInstId && scene"
          class="footer-button"
        >
          <v-icon
            size="48rpx"
            src="@/static/icons/service-icon.svg"
          />
          <view class="button-text">
            客服
          </view>
          <view class="footer-button-float">
            <contact-button
              :tnt-inst-id="tntInstId"
              :scene="scene"
              size="48rpx"
              icon="/static/icons/service-blank.svg"
            />
          </view>
        </view>
        <view
          class="footer-button"
          @click="switchToCart"
        >
          <v-icon
            size="48rpx"
            src="@/static/icons/product-details-cart.svg"
          />
          <view class="button-text">
            购物车
          </view>
        </view>
        <view class="footer-button-group">
          <view
            class="group-button add-cart"
            @click="showOrder('cart')"
          >
            加入购物车
          </view>
          <view
            class="group-button buy-immediately"
            @click="showOrder('order')"
          >
            立即下单
          </view>
        </view>
      </view>
    </template>
    <template #popup>
      <product-details-select-popup
        v-if="product"
        v-model:show="isShowSelect"
        :type="orderType"
        :product="product"
      />
    </template>
  </v-page>
</template>

<script setup lang="ts">
import ProductDetailsSelectPopup from './modules/product-details-select-popup.vue';
import ProductCommentTagList from './modules/product-comment-tag-list.vue';
import ProductCommentContent from './modules/product-comment-content.vue';
import ProductCommentGroupContent from './modules/product-comment-group-content.vue';

const refreshing = ref(false);
const productId = ref('');
const product = ref<SpuVO>();
const merchant = ref<MerchantVO>();
const loading = ref(true);

const tntInstId = computed(() => {
  if (merchant.value?.customer_service_status !== 'ENABLED') return undefined;
  return merchant.value?.customer_service_setting?.tenant_id;
});
const scene = computed(() => {
  if (merchant.value?.customer_service_status !== 'ENABLED') return undefined;
  return merchant.value?.customer_service_setting?.chat_window_id;
});

const splitApplauseRate = computed(() => {
  const positiveRate = comments.value?.positive_rate || 0;
  const rate = positiveRate * 100;
  const [before = '0', after = '0'] = rate.toFixed(2).split('.');
  return { before, after };
});

const score = computed(() => {
  const positiveRate = comments.value?.positive_rate ?? 0;
  return positiveRate * 5;
});

const getDetails = async () => {
  const response = await $api.getSearchIdDetail(productId.value);
  switch (response.__error) {
    case undefined:
      product.value = response.data;
      break;
  }
};
const comments = ref<SpuOrderCommentVO>();
const tagList = computed(() => {
  const list: { id?: string; name: string; count: number }[] = [];
  (comments.value?.comment_tags ?? [])
    .sort((a, b) => a.sort - b.sort)
    .forEach((tag) => {
      list.push({ id: tag.id, name: tag.tag_name, count: tag.tag_count });
    });
  (comments.value?.group_comment_tags ?? []).forEach((tag) => {
    const num = parseInt(tag.cnt);
    if (!isNaN(num) && num) {
      const item = list.find((item) => item.name === tag.tag_name);
      if (item) {
        item.count += num;
      } else {
        list.push({ name: tag.tag_name, count: num });
      }
    }
  });
  return list;
});
const activeTag = ref<{ id?: string; name: string }>();
const clickTagHandle = (tag?: { id?: string; name: string }) => {
  initList();
  activeTag.value = tag;

  getList();
};

const commentList = ref<SpuCommentVO[]>([]);
const groupCommentList = ref<SpuCommentGroupCommentOrderVO[]>([]);
const commentSum = computed(() => {
  const total = comments.value?.comment_sum ?? 0;
  return total > 9999 ? '1w+' : total;
});

const commentPageIndex = ref(1);
const commentState = ref<'loading' | 'finished' | 'error'>();
const getCommentList = async () => {
  if (!product.value?.id) return;
  if (commentState.value !== undefined && commentState.value !== 'error') {
    return;
  }
  commentState.value = 'loading';
  const response = await $api.getOrderCommentSpuid(product.value.id, {
    page_no: commentPageIndex.value,
    comment_tag_id: activeTag.value ? activeTag.value.id ?? '' : undefined,
    page_size: 10
  });
  switch (response.__error) {
    case undefined:
      comments.value = response.data;
      commentList.value.push(...(response.data?.comments ?? []));
      commentPageIndex.value++;
      if (!response.data.comments?.length || response.data.comments.length < 10) {
        commentState.value = 'finished';
      } else {
        commentState.value = undefined;
      }
      break;
    default:
      commentState.value = 'error';
  }
};

const groupCommentPageIndex = ref(1);
const groupCommentState = ref<'loading' | 'finished' | 'error'>();
const getGroupCommentList = async () => {
  if (!product.value?.id) return;
  if (
    groupCommentState.value !== undefined &&
    groupCommentState.value !== 'error'
  ) {
    return;
  }
  groupCommentState.value = 'loading';
  const response = await $api.getOrderCommentGroupCommentSpuid(
    product.value.id,
    {
      page_no: groupCommentPageIndex.value,
      tag_name: activeTag.value && activeTag.value.name,
      page_size: 10
    }
  );
  switch (response.__error) {
    case undefined:
      groupCommentList.value.push(...(response.data?.list ?? []));
      groupCommentPageIndex.value++;
      if (groupCommentList.value.length >= response.data.total) {
        groupCommentState.value = 'finished';
      } else {
        groupCommentState.value = undefined;
      }
      break;
    default:
      groupCommentState.value = 'error';
  }
};

const state = computed(() => {
  if (commentState.value === 'error') return 'error';
  if (groupCommentState.value === 'error') return 'error';
  if (commentState.value === 'loading') return 'loading';
  if (groupCommentState.value === 'loading') return 'loading';
  if (
    commentState.value === 'finished' ||
    groupCommentState.value === 'finished'
  ) {
    return 'finished';
  }
  return undefined;
});

const initList = () => {
  activeTag.value = undefined;
  commentList.value = [];
  commentPageIndex.value = 1;
  commentState.value = undefined;
  groupCommentList.value = [];
  groupCommentPageIndex.value = 1;
  groupCommentState.value = undefined;
};

const getList = async () => {
  await Promise.all([getCommentList(), getGroupCommentList()]);
};

onLoad(async (query) => {
  loading.value = true;
  productId.value = query?.id as string;
  await getDetails();
  await getList();
  loading.value = false;
});

const switchToCart = () => {
  uni.switchTab({ url: '/pages/cart/cart-page' });
};

const isShowSelect = ref(false);
const orderType = ref<'cart' | 'order'>('cart');
const showOrder = (type: 'cart' | 'order') => {
  orderType.value = type;
  isShowSelect.value = true;
};
</script>

<style lang="scss" scoped>
.comment-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  background: linear-gradient(
    180deg,
    rgba(255, 47, 59, 0.1) 0%,
    rgba(255, 255, 255, 0.1) 100%
  );
  padding: 0 32rpx;

  .comment-title {
    display: flex;
    align-content: center;

    .comment-title-before_rate {
      font-weight: 700;
      font-size: 40rpx;
      color: #ff2f3b;
      line-height: 24rpx;
    }
    .comment-title-after_rate {
      font-weight: 700;
      font-size: 28rpx;
      color: #ff2f3b;
    }
    .comment-title-text {
      margin-left: 12rpx;
      font-weight: 400;
      font-size: 28rpx;
      color: #ff2f3b;
    }
  }
}

.comment-subtitle {
  font-weight: 800;
  font-size: 28rpx;
  line-height: 70rpx;
  color: #333333;
  padding: 0 24rpx;
}

.comment-list {
  position: relative;
  padding: 0 24rpx;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 20rpx;
}

.product-details {
  background-color: white;
  border-radius: 16rpx 16rpx 0 0;
  .product-details-header {
    line-height: 93rpx;
    padding: 0 48rpx;
    font-weight: bold;
    font-size: 32rpx;
  }
}

.product-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24rpx;
  height: 100rpx;
  .footer-button {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6rpx;
    width: 70rpx;
    .button-text {
      font-size: 22rpx;
    }
    .footer-button-float {
      position: absolute;
      z-index: 1;
      top: 50%;
      left: 50%;
      height: 50rpx;
      width: 50rpx;
      transform: translate(-50%, -50%);
    }
  }
  .footer-button-group {
    display: flex;
    .group-button {
      width: 267rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 28rpx;
      font-weight: bold;
    }
    .add-cart {
      color: #ff2f3b;
      background-color: rgba(255, 47, 59, 0.102);
      border-radius: 40rpx 0 0 40rpx;
    }
    .buy-immediately {
      color: white;
      background-color: #ff2f3b;
      border-radius: 0 40rpx 40rpx 0;
    }
  }
}
</style>
